package deng.qiya.baidu;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import deng.qiya.model.BaiduGeocoderResult;
import deng.qiya.model.BaiduLocation;
import deng.qiya.model.HotelMapInfo;
import deng.qiya.util.XMLConverter;
import deng.qiya.wechat.Constant;
import deng.qiya.wechat.HomeController;

//hello world git
//from home
public class BaiduMap {
	@Autowired
	private XMLConverter xmlConverter;

	private static final Logger logger = LoggerFactory.getLogger(BaiduMap.class);
	
	public BaiduGeocoderResult getPlace(String query) {
		HttpClient httpClient = new DefaultHttpClient();
		try {
			
			HttpGet httpget = new HttpGet(requrl(query));
			ResponseHandler<String> responseHandler = new BasicResponseHandler();
			String responseBody = httpClient.execute(httpget, responseHandler);
			logger.info("baidu map result:" + responseBody);
			BaiduGeocoderResult baiduResult = (BaiduGeocoderResult)xmlConverter.convertFromStringXMLObjectToObject(responseBody);
			return baiduResult;
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		finally{
			httpClient.getConnectionManager().shutdown();
		}
		return null;
	}

	public String requrl(String query) {
		String url = null;
		try {
			url = Constant.baseUrl + "&address=" + URLEncoder.encode(query,"UTF-8") + "&key="
					+ Constant.mapKey + "&output=" + Constant.outputFormat;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return url;
	}
	//test git featuer again
	
	//TODO need adjust sometimes
	public static  String getStaticPic(BaiduLocation baiduLocation, List<HotelMapInfo> lists){
		StringBuffer buffer = new StringBuffer();
		buffer.append(Constant.BAIDU_STATIC_BASE_URL);
		buffer.append("center="+baiduLocation.getLng()+","+baiduLocation.getLat());
		buffer.append("&width=400&height=300&zoom=11");
		buffer.append("&markers=");
		for(HotelMapInfo hmi: lists){
			buffer.append(hmi.getLat()+","+hmi.getLng()+"|");
		}
		buffer.substring(0, buffer.length()-2);
		
		logger.info(buffer.toString());
		
		buffer.append("&markerStyles=");
		int i = 1;
		for(@SuppressWarnings("unused") HotelMapInfo hmi: lists){
			buffer.append("l"+","+i+"|");
			i++;
		}
		buffer.substring(0, buffer.length()-2);
		
		return buffer.toString();
	}
	
}
